require 'dgo/table/table'
require 'dgo/tile_map/collision_type'

module MapEditor
  module MapControler
    class CollisionSetter
      include DGO::TileMap
      def initialize(model)
        @model = model
      end
      
      def target=(target)
        @target = target
      end
    
      def set_default_frame(x, y)
        @map_panel.sx, @map_panel.sy = @map_panel.get_abs_location(x, y)
        @map_panel.ex = @map_panel.sx
        @map_panel.ey = @map_panel.sy
        @map_panel.frame.set_size(1, 1)        
      end
      
      def set_collision
        tx = @map_panel.sx
        ty = @map_panel.sy
        @model.map.collision_data[tx, ty] = CollisionType::ALL
      end
      
      def reset_collision
        tx = @map_panel.sx
        ty = @map_panel.sy
        @model.map.collision_data[tx, ty] = CollisionType::NONE
      end
      
      def on_double_clicked(event)
      
      end
      
      def on_left_down(event)
        self.set_collision
        @map_panel.invalidate(true, 0, 0, 1, 1)
      end
      
      def on_left_up(event)
      
      end
      
      def on_right_down(event)
        self.reset_collision
        @map_panel.invalidate(true, 0, 0, 1, 1)
      end
      
      def on_right_up(event)

      end
      
      def on_motion_right(event)
        self.reset_collision
        return 0, 0, 1, 1
      end
      
      def on_motion_left(event)
        self.set_collision
        return 0, 0, 1, 1
      end
      
      def on_motion(event)
        @mode = :put
        tx, ty, tw, th = 0, 0, 0, 0
        if @map_panel.right_pressed
          tx, ty, tw, th = self.on_motion_right(event) 
        end
        if @map_panel.left_pressed
          tx, ty, tw, th = self.on_motion_left(event) 
        end
        self.set_default_frame(event.x, event.y)
        @map_panel.invalidate(true, tx, ty, tw, th)
      end#

      def render(s)
        grid_width = @map_panel.grid_width
        grid_height = @map_panel.grid_height
        (0..@map_panel.x_count).each do |i|
          (0..@map_panel.y_count).each do |j|
            tx = @map_panel.scroll_x_count + i
            ty = @map_panel.scroll_y_count + j
            if @model.map.collision_data[tx, ty] == CollisionType::ALL
              s.render_rect(i * grid_width, j * grid_height, grid_width, grid_height, Color.new(255, 0, 0, 150))
            end
          end
        end

        @map_panel.frame.render(s, grid_width, grid_height,[@map_panel.sx, @map_panel.ex].min - @map_panel.scroll_x_count, [@map_panel.sy, @map_panel.ey].min - @map_panel.scroll_y_count)
      end
    end
  end
end